import json
import time

import requests
from loguru import logger
from requests import Session

from Common.CollegeMap import college_map
from Util.EncoderUtil import encode, decode
from config.Env import SystemUserInfo
from schemas import Page
from schemas.Page import PageCreate
from schemas.Activity import Activity


class ActivityServe:

    def getList(db: Session, page: PageCreate):
        timestamp = int(time.time() * 1000)
        paramsPage = f'{{"pageNum":{page.pageNum},"pageSize":{page.pageSize},"sortType":{page.sortType},"status":"{page.status}"}}'
        paramsToken = f'{{"token":"{SystemUserInfo.get_token()}","platform":3,"version":"2.0.5","device":"FAAE6E21-013F-42D1-B722-599DE3DC340F","timestamp":{timestamp}}}'
        try:
            # 发起请求
            response = requests.get(
                "https://ekta.jjvu.jx.cn/api/app/client/v1/page/activity/list",
                params={"params": encode(paramsPage)},
                headers={"Authorization": encode(paramsToken)}
            )
            # 解密响应
            decrypted_string = decode(response.text)
            if not decrypted_string:
                raise Exception("getPagelist 解密结果为空字符串")
            # 解析JSON
            decrypted_json = json.loads(decrypted_string)
            # 转为 Activity 对象数组
            data_list = decrypted_json["data"]['list']
            activity_list = [Activity(**item) for item in data_list]
            for activity in activity_list:
                keys = activity.collegeLimit.split(',')
                values = [college_map.get(key.strip()) for key in keys if key.strip()]
                activity.collegeLimit = ','.join(values)
                activity.endTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(activity.endTime / 1000))
                activity.startTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(activity.startTime / 1000))
                activity.enrollEndTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(activity.enrollEndTime / 1000))
                activity.enrollStartTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(activity.enrollStartTime / 1000))

            return activity_list
        except Exception as e:
            logger.error(f"getPagelist 函数内部错误: {e}")
            return None


